package com.example.lianguisystem.controller;

import com.example.lianguisystem.DTO.MaterialRequisitionDTO;
import com.example.lianguisystem.common.Result;
import com.example.lianguisystem.entity.*;
import com.example.lianguisystem.mapperLianGui.*;
import com.example.lianguisystem.service.CommonService;
import com.example.lianguisystem.service.MaterialRequisitionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/materialRequisition")
@CrossOrigin
public class MaterialRequisitionController {

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private MaterialRequisitionService service;

    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private SalesOrderMapper salesOrderMapper;

    @Autowired
    private LabelStatusMapper labelStatusMapper;
    @Autowired
    private IDrawMapper iDrawMapper;
    @Autowired
    private IDrawdetailMapper iDrawdetailMapper;

    @Autowired
    private MaterialRequisitionMapper materialRequisitionMapper;
    @GetMapping("/scanOrderlQr")
    public Result scanOrderlQr(@RequestParam("orderBillCode") String orderBillCode) {
        List<Map<String, Integer>> billMap = salesOrderMapper.selectMmBillidByMmBillcode(orderBillCode);
        if (billMap.size() <= 0) {
            return Result.fail("加工单未审核或无单身");
        }
        List<Integer> list = billMap.stream().map(map -> map.get("billid")).collect(Collectors.toList());
        List<Map<String, Object>> mapList = materialRequisitionMapper.selectDetailData(list, billMap.get(0).get("workshopid"));
        List<String> resultList = new ArrayList<>();
        List<String> goodsNoList = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            resultList.add((String) map.get("GoodsName"));
            goodsNoList.add((String) map.get("GoodsCode"));
        }
        Map<String, Object> res = new HashMap<>();
        res.put("goodsNoList", goodsNoList);
        res.put("goodsNameList", resultList);
        return Result.success(res);
    }
    @GetMapping("/scanLabelQr")
    public Result scanLabelQr(@RequestParam("label") String label) {
        LianGuiLabelRecord lianGuiLabelRecord = labelMapper.selectByLabel(label);
        if (lianGuiLabelRecord == null) {
            return Result.fail("标签不存在");
        }
        LianGuiLabelStatus lianGuiLabelStatus = labelStatusMapper.selectLabelStatusOfNotGet(lianGuiLabelRecord.getId());
        if (lianGuiLabelStatus != null) {
            Date recordDate = lianGuiLabelStatus.getRecordDate();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy年M月d日 H点m分");
            String format = simpleDateFormat.format(recordDate);
            return Result.fail("标签已被" + lianGuiLabelStatus.getRecordBy() + "于" + format + "扫描领料");
        }
        return Result.success(lianGuiLabelRecord);
    }

    @PostMapping("/submit")
    @Transactional(rollbackFor = Exception.class, transactionManager = "lianGuiTransactionManager")
    public Result submit(@RequestBody List<MaterialRequisitionDTO> materialRequisitionDTOList, @RequestParam("username") String username) {
        List<String> collectLabelId = new ArrayList<>();
        for (MaterialRequisitionDTO materialRequisitionDTO : materialRequisitionDTOList) {
            List<String> collect = materialRequisitionDTO.getList().stream().map(LianGuiLabelRecord::getId).collect(Collectors.toList());
            collectLabelId.addAll(collect);
        }
        List<LianGuiLabelStatus> lianGuiLabelStatuses = labelStatusMapper.selectLabelStatusOfNotGetList(collectLabelId);
        if (lianGuiLabelStatuses.size() > 0) {
            List<String> collect = lianGuiLabelStatuses.stream().map(LianGuiLabelStatus::getLabel).collect(Collectors.toList());
//            return Result.fail("标签已领料: " + collect);
        }

        ZoneId zoneId = ZoneId.systemDefault();
        LocalDate localDate = LocalDate.now();
        ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
        Date date = Date.from(zdt.toInstant());
        Map<String, Object> userDataMap = commonMapper.selectUserData(username);

        List<String> collect = materialRequisitionDTOList.stream().map(MaterialRequisitionDTO::getTitle).collect(Collectors.toList());
        List<SalesOrder> salesOrderList = materialRequisitionMapper.selectDataByMmCode(collect);
        Map<String, Map<String, Object>> tempMap = new HashMap<>();
        Set<Integer> workshopSet = new HashSet<>();
        for (SalesOrder salesOrder : salesOrderList) {
            Map<String, Object> map = new HashMap<>();
            map.put("wrokshop", salesOrder.getWorkshop());
            map.put("billid", salesOrder.getProcessingBillid());
            map.put("price", salesOrder.getUnitPrice());
            tempMap.put(salesOrder.getProcessingBillcode(), map);
            workshopSet.add(salesOrder.getWorkshop());
        }
        for (MaterialRequisitionDTO materialRequisitionDTO : materialRequisitionDTOList) {
            Map<String, Object> map = tempMap.get(materialRequisitionDTO.getTitle());
            materialRequisitionDTO.setWorkshop((Integer) map.get("wrokshop"));
            materialRequisitionDTO.setBillId((Integer) map.get("billid"));
            materialRequisitionDTO.setPrice((Double) map.get("price"));
        }
        for (Integer workshop : workshopSet) {
            List<MaterialRequisitionDTO> groupByWorkshop = materialRequisitionDTOList.stream().filter(item -> item.getWorkshop() == workshop).collect(Collectors.toList());
            IDraw iDraw = service.getIDraw(date, userDataMap, groupByWorkshop.get(0).getWorkshop());
            List<IDrawdetail> iDrawdetailList = service.getIDrawdetail(groupByWorkshop);
            double amount = iDrawdetailList.stream().mapToDouble(IDrawdetail::getAmount).sum();
            iDraw.setAmount(amount);
            String pre = "DR-";
            synchronized (this) {
                String drBillcode = commonService.getBillCode(pre, "i_draw");
                Integer drBillid = commonMapper.selectMaxBiillidByTableName("i_draw");
                iDraw.setBillid(drBillid);
                iDraw.setBillcode(drBillcode);
                for (IDrawdetail iDrawdetail : iDrawdetailList) {
                    iDrawdetail.setBillid(drBillid);
                }
                iDrawMapper.insert(iDraw);
                for (IDrawdetail iDrawdetail : iDrawdetailList) {
                    iDrawdetailMapper.insert(iDrawdetail);
                }
                DateTimeFormatter tempDtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                String format = LocalDate.now().format(tempDtf);
                commonMapper.execup_ab_billprint_insert(25, drBillid, drBillcode, format, iDraw.getOpid(), iDraw.getShopid());
                for (MaterialRequisitionDTO materialRequisitionDTO : groupByWorkshop) {
                    List<LianGuiLabelRecord> list = materialRequisitionDTO.getList();
                    for (LianGuiLabelRecord origin : list) {
                        LianGuiLabelRecord lianGuiLabelRecord = new LianGuiLabelRecord();
                        lianGuiLabelRecord.setId(origin.getId());
                        lianGuiLabelRecord.setStatus((byte) 4);
                        labelMapper.updateById(lianGuiLabelRecord);
                        LianGuiLabelStatus lianGuiLabelStatus = new LianGuiLabelStatus();
                        lianGuiLabelStatus.setLabelId(lianGuiLabelRecord.getId());
                        lianGuiLabelStatus.setStatus(lianGuiLabelRecord.getStatus());
                        lianGuiLabelStatus.setRecordDate(new Date());
                        lianGuiLabelStatus.setRecordBy(username);
                        lianGuiLabelStatus.setBillid(drBillid);
                        lianGuiLabelStatus.setBillcode(drBillcode);
                        labelStatusMapper.insertIntoLabelStatus(lianGuiLabelStatus);
                    }
                }
            }

        }
        return Result.success();
    }
}
